import {Crypto} from './crypto-min.js';
import axios from "axios";

const Base64 = require('js-base64').Base64;
const config = {headers: {'Accept': 'application/json, text/javascript, */*; q=0.01'}};
const policyText = {
    "expiration": "2099-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

export function upload(data, file) {
    let policyBase64 = Base64.encode(JSON.stringify(policyText));
    let bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, data.accesskey, {asBytes: true});
    let signature = Crypto.util.bytesToBase64(bytes);

    let multipart_params = formData({
        'key': `${data.key + getFileName(file.name)}`,
        'policy': policyBase64,
        'success_action_status': 200,
        'OSSAccessKeyId': data.OSSAccessKeyId,
        'signature': signature,
        'file': file.raw
    });

    return axios.post('https://global-application-001.downline.cn', multipart_params, config).then(() => {
        return 'https://global-application-001.downline.cn/' + multipart_params.get('key')
    })

    // return http.post('https://global-application-001.downline.cn', multipart_params, config).then(() => {
    //     return process.env.VUE_APP_OSS_URL + '/' + multipart_params.get('key')
    // })
}

/** 对象转换为formData类型 */
function formData(obj) {
    if (obj instanceof Object) {
        let multipart_params = new FormData();
        for (let key in obj) {
            multipart_params.append(key, obj[key]);
        }
        return multipart_params;
    }
    return;
}

/** 生成随机文件名 格式为随机6位数+时间戳+文件类型 */
function getFileName(filename) {
    let pos = filename.lastIndexOf('.')
    if (pos != -1) {
        return randomString(6) + new Date().getTime() + filename.substring(pos - 1);
    }
    return '';
}

/** 随机数 未指定长度则为32位 */
function randomString(len) {
    len = len || 32;
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let maxPos = chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
